package com.kude.action;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;

import com.kude.entity.Product;
import com.kude.entity.ProductCategory;
import com.kude.entity.ProductCategoryPrefix;
import com.kude.manager.OperException;
import com.kude.service.ProductCategoryPrefixService;
import com.kude.service.ProductCategoryService;
import com.kude.service.ProductService;
import com.kude.util.BeanFactory;

public class GetProductServlet extends HttpServlet {
	ProductService productService;
	ProductCategoryService productCategoryService;
	ProductCategoryPrefixService productCategoryPrefixService;

	/**
	 * Constructor of the object.
	 */
	public GetProductServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		productService = BeanFactory.getBean(ProductService.class.getName());
		productCategoryService = BeanFactory.getBean(ProductCategoryService.class.getName());
		productCategoryPrefixService = BeanFactory.getBean(ProductCategoryPrefixService.class.getName());
		String operation = request.getParameter("operation");
		System.out.println("11111111111111111");
		if (operation.equals("add")) {
			try {
				this.add(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("update")) {
			try {
				this.update(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("delete")) {
			try {
				this.delete(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getProductByisOnsale")) {
			try {
				this.getProductByIsOnsale(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getProductByisNew")) {
			try {
				this.getProductByIsNew(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getTopParentProduct")) {
			try {
				this.getTopParentProduct(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getSecondParentProduct")) {
			try {
				this.getSecondParentProduct(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getLastLevelProduct")) {
			try {
				this.getLastLevelProduct(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获得属于最后一层类别的产品，如YY牌子的羽毛球拍
	 * 
	 * @param categoryId
	 *            最后一层类别ID
	 * @param pageNow
	 * @param pageSize
	 * @throws Exception
	 * @throws Exception
	 * @throws Exception
	 */
	private void getLastLevelProduct(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int categoryId = Integer.parseInt(request.getParameter("categoryId"));
		int pageNow = Integer.parseInt(request.getParameter("pageNow"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		ArrayList productCategoryList = new ArrayList();
		productCategoryList.add(productCategoryService.getProductCategory(categoryId));
		System.out.println(productCategoryList.size()+"kkkkkkkkkkkkkkkkkkkkkkkk");
		ArrayList productList = (ArrayList) productService.getProductListByCategoryIdList(pageNow, pageSize,productCategoryList);
		System.out.println(productList.size()+"gggggggggggggg");
		
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("productCategory")||name.equals("products")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		JSONArray lastLevelProductList = JSONArray
				.fromObject(productList,config);
		
		response.getWriter().write(lastLevelProductList.toString());
		response.getWriter().flush();
	}

	/**
	 * 获得属于第二层类别的产品，如YY牌子 KK牌子
	 * 
	 * @param categoryId
	 *            第二层类别ID
	 * @param pageNow
	 * @param pageSize
	 * @throws Exception
	 * @throws Exception
	 */
	private void getSecondParentProduct(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int categoryId = Integer.parseInt(request.getParameter("categoryId"));
		int pageNow = Integer.parseInt(request.getParameter("pageNow"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		ProductCategory productCategory = productCategoryService
				.getProductCategory(categoryId);
		ArrayList productCategoryList = (ArrayList) productService
				.getProductListByCategoryIdList(pageNow, pageSize,
						productCategoryService.getProductCategoryListByPrefix(productCategory
										.getPrefix()));
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("productCategory")||name.equals("products")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		JSONArray secondParentproductList = JSONArray.fromObject(productService
				.getProductListByCategoryIdList(pageNow, pageSize,
						productCategoryList),config);
		response.getWriter().write(secondParentproductList.toString());
		response.getWriter().flush();
	}

	/**
	 * 获得属于顶层类别的产品，如羽毛球用品、网球用品
	 * 
	 * @param categoryId
	 *            顶层类别ID
	 * @param pageNow
	 * @param pageSize
	 * @throws Exception
	 */
	private void getTopParentProduct(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int categoryId = Integer.parseInt(request.getParameter("categoryId"));
		int pageNow = Integer.parseInt(request.getParameter("pageNow"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		ProductCategoryPrefix productCategoryPrefix = productCategoryPrefixService
				.getProductCategoryPrefixById(categoryId);
		ArrayList productCategoryList = (ArrayList)productCategoryService
				.getProductCategoryListByPrefix(productCategoryPrefix
						.getPrefix());
		
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("productCategory")||name.equals("products")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        
		JSONArray topParentproductList = JSONArray.fromObject(productService
				.getProductListByCategoryIdList(pageNow, pageSize,
						productCategoryList),config);
		response.getWriter().write(topParentproductList.toString());
		response.getWriter().flush();
	}

	private void getProductByIsNew(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int isNew = Integer.parseInt(request.getParameter("isNew"));
		int pageNow = Integer.parseInt(request.getParameter("pageNow"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));

		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("productCategory")||name.equals("products")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        
		JSONArray productIsNewList = JSONArray.fromObject(productService
				.getProductByIsOnsale(pageNow, pageSize, isNew),config);
		response.getWriter().write(productIsNewList.toString());
		response.getWriter().flush();
	}

	private void getProductByIsOnsale(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int isOnSale = Integer.parseInt(request.getParameter("isOnsale"));
		int pageNow = Integer.parseInt(request.getParameter("pageNow"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		System.out.println("isOnsale"+isOnSale);
		System.out.println("pageNow"+pageNow);
		System.out.println("pageSize"+pageSize);
		
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("productCategory")||name.equals("products")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        
		JSONArray productIsOnsaleList = JSONArray.fromObject(productService
				.getProductByIsOnsale(pageNow, pageSize, isOnSale),config);
		response.getWriter().write(productIsOnsaleList.toString());
		response.getWriter().flush();
	}

	private void delete(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int id = Integer.parseInt(request.getParameter("productId"));
		try {
			productService.deleteProduct(id);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}

	}

	private void update(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int id = Integer.parseInt(request.getParameter("productId"));
		try {
			Product product = new Product();
			// TODO 把需要更改的字段更新
			productService.updateProduct(product);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}
	}

	private void add(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Product product = new Product();
		// TODO 更新字段值
		try {
			productService.addProduct(product);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (Exception e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
